package middlewares

import (
	"context"
	ctxconstans "gitee.com/zackeus/go-boot/common/constants/context"
	"gitee.com/zackeus/go-zero/core/logx"
	"net/http"
	"net/http/httputil"
)
import "gitee.com/zackeus/go-boot/tools/httpx"

func detailErrLog(w http.ResponseWriter, r *http.Request, err error) {
	if err == nil {
		return
	}
	// discard dump error, only for debug purpose
	details, _ := httputil.DumpRequest(r, true)
	logx.Errorf("httpx middleware failed: %s\n=> %+v", err.Error(), string(details))
}

func HttpxMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		/* 解析客户端IP 需要负载配合设置透传客户端IP */
		ip, err := httpx.ClientIP(r)
		if err != nil {
			detailErrLog(w, r, err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		/* context 保存客户端参数 */
		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxconstans.ClintIP, ip)))
	}
}
